package com.xzh.controller; /**
 * @Author XuZhuHong
 * @CreateTime 2021/6/1 12:08
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzh.bean.Employee;
import com.xzh.bean.Msg;
import com.xzh.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理crud
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //根据id删除员工方法
    @ResponseBody
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    public Msg deleteEmployee(@PathVariable("ids") String ids) {
        if (ids.contains("-")) {
            //批量删除
            List<Integer> list_ids=new ArrayList<>();
            String[] split = ids.split("-");
            for (String s : split) {
                list_ids.add(Integer.parseInt(s));
            }
            employeeService.deleteEmps(list_ids);
        } else {
            //单个删除
            employeeService.deleteEmp(Integer.parseInt(ids));
        }
        return Msg.success();
    }

    //修改员工信息
    @ResponseBody
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    public Msg saveEmp(Employee employee) {
        System.out.println(employee);
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    //查询员工的信息方法
    @ResponseBody
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    //PathVariable注解用来绑定restful 风格所绑定的数据
    //里面的值对应{}里面的值
    public Msg getEmp(@PathVariable("id") Integer id) {
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp", employee);
    }

    //检查用户名是否可用
    @RequestMapping("/checkuser")
    @ResponseBody
    public Msg checkuser(String empName) {
        //判断用户名是不是合法的表达式
        String regex = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        boolean matches = empName.matches(regex);
        if (!matches) {
            return Msg.fail().add("va_msg", "用户名必须是6-12位英文或者2-5个汉字");
        }
        boolean b = employeeService.checkUser(empName);
        if (b) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名已存在");
        }
    }

    //保存员工信息
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {
        //创建一个集合  然后把错误信息装进去
        Map< String, Object > map = new HashMap<>();
        //如果有失败的信息就封装进去
        if (result.hasErrors()) {
            //校验失败返回信息  在模态框中返回校验失败的信息
            List< FieldError > fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //循环保存
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            //添加到msg中
            return Msg.fail().add("errorFields", map);
        } else {
            //校验成功就返回
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }


    /**
     * ajax查询员工信息
     *
     * @param pn
     * @param model
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWidthJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
        //这是一个分页查询
        //引入分页插件
        //在查询之前调用   startPage(页码,每页显示)
        PageHelper.startPage(pn, 5);
        List< Employee > emps = employeeService.getAll();
        //将上面查询到的数据进行封装到分页中
        //new PageInfo<>(查询到的数据,连续显示的页数)
        PageInfo pageInfo = new PageInfo(emps, 5);
        //分页中的每一条数据用 pageInfo.list()可以取出
        return Msg.success().add("pageInfo", pageInfo);
    }

    /**
     * 查询员工数据
     *
     * @return
     */
//    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
        //这是一个分页查询
        //引入分页插件
        //在查询之前调用   startPage(页码,每页显示)
        PageHelper.startPage(pn, 5);
        List< Employee > emps = employeeService.getAll();
        //将上面查询到的数据进行封装到分页中
        //new PageInfo<>(查询到的数据,连续显示的页数)
        PageInfo pageInfo = new PageInfo(emps, 5);
        model.addAttribute("pageInfo", pageInfo);
        //分页中的每一条数据用 pageInfo.list()可以取出
        return "list";
    }

}
